package com.example.flinkcourse.lesson5.route;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.util.Collector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * 数据路由实现
 */
public class DataRouter {
    private static final Logger LOG = LoggerFactory.getLogger(DataRouter.class);
    private static final ObjectMapper objectMapper = new ObjectMapper();
    
    // 表名映射规则
    private static final Map<String, String> TABLE_MAPPING = new HashMap<>();
    
    static {
        // 初始化表名映射规则
        TABLE_MAPPING.put("orders", "ods_orders");
        TABLE_MAPPING.put("products", "ods_products");
        TABLE_MAPPING.put("order_items", "ods_order_items");
    }
    
    /**
     * 创建数据路由函数
     *
     * @return FlatMapFunction
     */
    public static FlatMapFunction<String, String> createRouter() {
        return new FlatMapFunction<String, String>() {
            @Override
            public void flatMap(String value, Collector<String> out) throws Exception {
                try {
                    // 解析 JSON 数据
                    JsonNode jsonNode = objectMapper.readTree(value);
                    
                    // 获取表名
                    String tableName = jsonNode.get("source").get("table").asText();
                    
                    // 获取目标表名
                    String targetTable = TABLE_MAPPING.get(tableName);
                    if (targetTable == null) {
                        LOG.warn("未找到表名映射规则: {}", tableName);
                        return;
                    }
                    
                    // 添加目标表名
                    ((com.fasterxml.jackson.databind.node.ObjectNode) jsonNode)
                        .put("target_table", targetTable);
                    
                    // 输出数据
                    out.collect(objectMapper.writeValueAsString(jsonNode));
                } catch (Exception e) {
                    LOG.error("数据路由失败: {}", value, e);
                }
            }
        };
    }
} 